import { defineStore } from 'pinia'

export const useUserStore = defineStore('user', {
  state: () => ({
    token: '',
    userInfo: {
      id: '',
      username: '',
      avatar: '',
      role: '',
    }
  }),

  getters: {
    isLoggedIn: (state) => !!state.token,
    isAdmin: (state) => state.userInfo.role === 'admin'
  },

  actions: {
    setToken(token) {
      this.token = token
      localStorage.setItem('token', token)
    },

    setUserInfo(userInfo) {
      this.userInfo = userInfo
    },

    async login(username, password) {
      try {
        // TODO: 调用登录接口
        const res = await fetch('/api/login', {
          method: 'POST',
          body: JSON.stringify({ username, password })
        })
        const data = await res.json()
        this.setToken(data.token)
        this.setUserInfo(data.userInfo)
        return data
      } catch (error) {
        console.error('登录失败:', error)
        throw error
      }
    },

    logout() {
      this.token = ''
      this.userInfo = {
        id: '',
        username: '',
        avatar: '',
        role: ''
      }
      localStorage.removeItem('token')
    }
  },

  persist: {
    enabled: true,
    strategies: [
      {
        key: 'user-state',
        storage: localStorage,
        paths: ['token', 'userInfo']
      }
    ]
  }
})